//
//  OAuthViewController.swift
//  0110-weibo
//
//  Created by 鲍志刚 on 16/1/12.
//  Copyright © 2016年 zhongye. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    //MARK:关闭页面
    @objc private func close(){
    
        //dismiss页面
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func defaultAccount() {
    
    let jsString = "document.getElementById('userId').value = '1002344082@qq.com', document.getElementById('passwd').value = 'gang1314'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    }
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //文字渲染颜色
        //只对当前的导航试图控制器有效
//        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        //一经设置 全局有效
//        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        //

        //设置导航条
        setNavBar()
        
        //加载授权页面
        loadOAuthPage()
    
    }
    
   private func setNavBar(){
        
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self , action: "close")
    
    
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAccount")

    }
    
    
    //MARK:加载授权页面
   private func loadOAuthPage(){
    
    let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
    
    //可选的url
    let url = NSURL(string: urlString)!
    //获取request
    let request = NSURLRequest(URL: url)
    
    webView.loadRequest(request)
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


//swift中 这样写 是将一类的协议方法 写在一起 更加好阅读 和维护
//同一类的协议方法就被放在一个扩展中

extension OAuthViewController : UIWebViewDelegate {

    //显示
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //隐藏
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //非常重要的协议方法
    //通常协议方法返回值 为bool 类型  返回 yes 通常控件可以正常返回
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //截取URL中的code授权码
        
//         print(request.URL?.absoluteString)
        guard let urlString = request.URL?.absoluteString else {
        
        //无法获取 URL 的字符串 就直接不加载网页
            return false
        }
        
        if urlString.containsString("code=") {
        
//        print(urlString)
            
//            print(request.URL?.query)
            
        //将URL中的参数获取到
            guard let query = request.URL?.query else {
            
                return false
            }
            
            let codeStr = "code="
            //将query 转换NSString  subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
//            print(code,query)
            
            //调用 获取 token的方法
            loadAccessToken(code)
            
            //不希望页面跳转到 回调页面
    return false
            
        }

        return true
    }
    
    
    private func loadAccessToken(code : String ){
    
        //请求token 和用户数据
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
        
            
            if !isSuccess {
                
                print("用户登录失败")
                ////HUD 提示用户 登录失败
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                
                return
            
            }
            
            
            //一定登录成功
            SVProgressHUD.showSuccessWithStatus("登录成功")
            // //执行dismiss操作的时候 HomeTableView没有真正的释放掉
            //执行dismiss操作 对应的页面不会正在的销毁
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //通知是同步的还是异步的
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "Welcome")
                
                 print("come here")
            })
            
            //切换根视图 不推荐这样写
//                        UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
            
            
        }
        
    
    }


}



